package org.example.SolutionNew002;

public class LinkedList02 {
    public static void main(String[] args) {
        LinkedList02 l = new LinkedList02();
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        ListNode res=l.reverseList(head);
        while(res!=null){
            System.out.println(res.val);
            res=res.next;
        }
    }

    public ListNode reverseList1(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode prev = null;
        ListNode nextHead;
        while(head!=null){
            nextHead = head.next;
            head.next = prev;
            prev = head;
            head = nextHead;
        }
        return prev;
    }

    //递归，从后往前
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode NewNode=reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return NewNode;
    }
}
